<template>
	<div style="width: 100%;">
		<div ref="uiwuEditor" style="width: 100%;height: 500px;"></div>
		<uw-image-manager v-if="showImageManager" isMultiple @change="changeImage" />
	</div>
</template>

<script setup lang="ts">
	/**
	 * 富文本编辑器
	 * @author: uiwu
	 * @date: 2022-12-12 15:22
	 */
	import Quill from 'quill';
	import { nextTick, onMounted, ref } from 'vue';
	interface ImageItem {
		url: string;
		categoryId:string,
		createdAt:string,
		fileName:string,
		id:string,
		selected:true,
		updatedAt:string
	}
	const props = defineProps({
		modelValue: {
			type: String,
			default: ''
		},
		placeholder: {
			type: String,
			default: '请输入'
		}
	});
	const showImageManager = ref(false);
	const emit = defineEmits(['update:modelValue']); // 增加自定义事件
	const uiwuEditor = ref(null);
	let quill: Quill | null = null; // 保存 Quill 实例
	const options : any = {
		modules: {
			toolbar: {
				container: [
					[{ header: '1' }, { header: '2' }, { font: [] }],
					[{ list: 'ordered' }, { list: 'bullet' }],
					[{ script: 'sub' }, { script: 'super' }],
					[{ indent: '-1' }, { indent: '+1' }],
					[{ direction: 'rtl' }],
					[{ size: ['small', false, 'large', 'huge'] }],
					[{ header: [1, 2, 3, 4, 5, 6, false] }],
					[{ color: [] }, { background: [] }],
					[{ align: [] }],
					['link', 'image', 'video']
				],
				handlers: {
					// 自定义图片按钮的点击行为
					image: () => {
						showImageManager.value = true
					}
				}
			},
			clipboard: {
				matchVisual: false
			},
			history: {
				delay: 2000,
				userOnly: true
			}
		},
		placeholder: props.placeholder,
		theme: 'snow'
	};
	/**
	 * 选择图片回调
	 */
	const changeImage = (list:ImageItem[]) => {
		showImageManager.value = false;
		if (!quill) return;
		list.forEach((image) => {
			// 获取当前光标位置
			const range = quill.getSelection();
			if (range) {
				// 插入图片到光标位置
				quill.insertEmbed(range.index, 'image', image.url);
				// 调整光标位置到图片后
				quill.setSelection(range.index + 1);
			}
		});
	}
	onMounted(() => {
		nextTick(() => {
			quill = new Quill(uiwuEditor.value, options);

			// 初始化内容
			quill.root.innerHTML = props.modelValue;

			// 监听文本变化
			quill.on('text-change', () => {
				emit('update:modelValue', quill.root.innerHTML);
			});
		});
	});
</script>

<style>
</style>